package com.suixinsanren.design.observer.demo03;

import java.util.ArrayList;
import java.util.List;

public class WeatherData implements Subject<Observer> {

    private final List<Observer> observerList;
    private float temperature;
    private float humidity;
    private float pressure;
    private boolean isChange;

    public WeatherData() {
        this.observerList = new ArrayList<>();
    }

    public void update(float temperature, float humidity, float pressure) {
        this.temperature = temperature;
        this.humidity = humidity;
        this.pressure = pressure;
        this.isChange = false;
        setChange();
        notifyObservers();
    }

    @Override
    public void registerObserver(Observer observer) {
        observerList.add(observer);
    }

    @Override
    public void removeObserver(Observer observer) {
        observerList.remove(observer);
    }

    @Override
    public void notifyObservers() {
        if (isChange) {
            observerList.forEach(observer -> observer.update(this.temperature, this.humidity, this.pressure));
        }
    }

    @Override
    public void setChange() {
        this.isChange = true;
    }

}
